(library (grid-gen OpenMP)

(export OpenMP:set-nproc
        OpenMP:args
        OpenMP:time:get-sec
        OpenMP:disable
)

(import (guile)
        (rnrs)
        (grid-gen main)
        (grid-gen code)
)

(define safe-sec code:get-sec)

(define OpenMP:set-nproc (lambda (n)
  (if (number? n)
      (set! OpenMP:nproc n)
  )
  (if (or (eq? n #t) (and (number? n) (> n 1)))
      (begin
        (set! CODE:enable-SMP #t)
        (set! time:get-sec OpenMP:time:get-sec)
      )
      (begin
        (set! CODE:enable-SMP #f)
        (set! time:get-sec safe-sec)
      )
  )
))

(define OpenMP:disable (lambda ()
  (set! CODE:enable-SMP #f)
  (set! time:get-sec safe-sec)
))

(define OpenMP:args (lambda args
  (if (= (length args) 1)
      (OpenMP:set-nproc (car args))
  )
))

(define omp-init (lambda (cod)
  (if OpenMP:nproc
      (list (car cod)
            (cons 'CODE_BEGIN
                   (append `((CODE_CALL "omp_set_num_threads" (,OpenMP:nproc))
                             (RAW "")
                            )
                            (cdr cod)
                   )
            )
      )
      cod
  )
))

(define OpenMP:time:get-sec (lambda (v)
  (set-val v '(omp_get_wtime))
))

)

(add-include "omp_lib.h")
(add-wrapper 11 'RUN_CODE omp-init)
(set! CODE:enable-SMP #t)
(set! SMP:disable OpenMP:disable)
;;(set! time:get-sec OpenMP:time:get-sec)
